package com.atguigu.spzx.manager.websocket;

import com.atguigu.spzx.manager.mapper.WebSocketMapper;
import com.atguigu.spzx.model.entity.system.SysUser;
import com.atguigu.spzx.utils.AuthContextUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.websocket.OnClose;
import javax.websocket.OnMessage;
import javax.websocket.OnOpen;
import javax.websocket.Session;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;
import java.util.Collections;
import java.util.HashSet;
import java.util.Set;

@Component
@ServerEndpoint("/websocket/{selectedContactId}")
public class WebSocketServer {

    @Autowired
    private WebSocketMapper webSocketMapper;

    // 用于存储 selectedContactId
    private String selectedContactId;

    //用于存储conversationId
    private Long conversationId;

    @OnOpen
    public void onOpen(Session session) {
        this.selectedContactId = selectedContactId; // 保存路径参数
        System.out.println("Connection opened: " + session.getId() + ", selectedContactId: " + selectedContactId);
        sessions.add(session);
        System.out.println("Connection opened: " + session.getId() );
        sessions.add(session);
    }

    @OnMessage
    public void onMessage(Session session, String message) throws IOException {

        System.out.println("Received message: " + message);
        session.getBasicRemote().sendText("Server received: " + message);
    }

    @OnClose
    public void onClose(Session session) {
        System.out.println("Connection closed: " + session.getId());
        sessions.remove(session);
    }


    private static final Set<Session> sessions = Collections.synchronizedSet(new HashSet<Session>());
}